"use client";

import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { Sun, Moon } from 'lucide-react';

// 主题类型
export type Theme = 'light' | 'dark';

interface ThemeSwitcherProps {
  size?: 'sm' | 'md' | 'lg';
  className?: string;
}

export const ThemeSwitcher = ({ size = 'md', className = '' }: ThemeSwitcherProps) => {
  // 初始化为null避免水合不匹配
  const [theme, setTheme] = useState<Theme | null>(null);
  
  // 计算尺寸
  const sizeClass = {
    sm: 'h-8 w-14',
    md: 'h-10 w-16',
    lg: 'h-12 w-20'
  }[size];
  
  const iconSize = {
    sm: 14,
    md: 16,
    lg: 20
  }[size];

  // 在客户端挂载后获取主题
  useEffect(() => {
    // 从本地存储获取当前主题或使用系统偏好
    const storedTheme = localStorage.getItem('theme') as Theme | null;
    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
    const initialTheme = storedTheme || (prefersDark ? 'dark' : 'light');
    
    setTheme(initialTheme);
    document.documentElement.setAttribute('data-theme', initialTheme);
    localStorage.setItem('theme', initialTheme);
  }, []);
  
  // 切换主题
  const toggleTheme = () => {
    if (!theme) return;
    
    const newTheme = theme === 'dark' ? 'light' : 'dark';
    setTheme(newTheme);
    document.documentElement.setAttribute('data-theme', newTheme);
    localStorage.setItem('theme', newTheme);
  };
  
  // 如果主题尚未确定，不要渲染按钮以避免闪烁
  if (theme === null) {
    return <div className={`${sizeClass} ${className} bg-indigo-600/20 rounded-full`}></div>;
  }
  
  return (
    <motion.button
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      onClick={toggleTheme}
      className={`
        ${sizeClass} 
        ${className}
        relative rounded-full p-1 
        bg-gradient-to-r from-indigo-500/20 to-emerald-500/20 border border-white/10
        hover:border-white/20 transition-colors
      `}
      aria-label={`Switch to ${theme === 'dark' ? 'light' : 'dark'} mode`}
    >
      <motion.div 
        className="absolute bg-white rounded-full"
        initial={false}
        animate={{
          x: theme === 'dark' ? '100%' : '0%',
          translateX: theme === 'dark' ? '-100%' : '0%'
        }}
        transition={{ type: "spring", stiffness: 300, damping: 30 }}
        style={{
          width: `calc(${sizeClass.split(' ')[1]} / 2)`,
          height: '80%',
          top: '10%'
        }}
      >
        {theme === 'dark' ? (
          <Moon size={iconSize} className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 text-indigo-950" />
        ) : (
          <Sun size={iconSize} className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 text-amber-500" />
        )}
      </motion.div>
    </motion.button>
  );
}; 